import utils from '@helpers/utils'
import * as c from 'colors'
import * as Koa from 'koa'
import * as winston from 'winston'

export function logger(winstonInstance: typeof winston) {
  return async (ctx: Koa.Context, next: () => Promise<any>) => {

    const start = new Date().getMilliseconds()

    await next()

    const ms = new Date().getMilliseconds() - start

    let logLevel: string = ''
    let responseText = ctx.body
    if (ctx.status >= 500) {
      const { name, stack, message } = ctx.error
      logLevel = 'error'
      responseText = `'( type: ${name || ''} ) { msg: ${message || ''} }, [ stack: ${stack || ''} ]'`
    } else if (ctx.status >= 400 && ctx.status < 500) {
      logLevel = 'warn'
    } else {
      logLevel = 'info'
    }

    const msg: string = `${ctx.method} ${ctx.originalUrl} ${ctx.status} ${ms}ms date: ${utils.parseTime(Date.now())}: [ Response: ${JSON.stringify(responseText)} ]`

    if (logLevel === 'info') {
      console.info(c.green(msg))
    } else {
      console.error(c.red(msg))
    }

    winstonInstance.configure({
      level: 'error',
      transports: [
        new winston.transports.File(
          {
            format: winston.format.combine(
              winston.format.colorize(),
              winston.format.simple()
            ),
            level: 'error'
          }
        ),
      ]
    })

    winstonInstance.log(logLevel, msg)
  }
}
